package com.common.data.desensitization.common.handler;

import com.common.data.desensitization.common.annotation.DesensitizationRule;
import com.common.data.desensitization.common.utils.RepeatMaskUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
@Component
public class DesensitizeMiddleMaskHandler implements DesensitizationHandler{
    @Override
    public String desensitize(String originalValue, DesensitizationRule rule) {
        if (originalValue.length() <= rule.prefixKeep() + rule.suffixKeep()) {
            if (originalValue.length() <= rule.prefixKeep()) return originalValue; //只保留前缀
            return  RepeatMaskUtil.repeatMask(originalValue.length(), rule.maskChar());
        }
        String prefix = originalValue.substring(0, rule.prefixKeep());
        String suffix = originalValue.substring(originalValue.length() - rule.suffixKeep());
        if (StringUtils.hasText(rule.middleReplaceString())) {
            return prefix + rule.middleReplaceString() + suffix;
        } else {
            int maskedLength = originalValue.length() - rule.prefixKeep() - rule.suffixKeep();
            return prefix +  RepeatMaskUtil.repeatMask(maskedLength, rule.maskChar()) + suffix;
        }
    }
}
